package mi.payment.settings;

import android.text.TextUtils;

import java.util.Locale;

import mi.payment.MyApplication;
import mi.payment.utils.SharedPreferencesUtil;
import sunmi.sunmiui.utils.LogUtil;

import static mi.payment.settings.SystemParamsSettings.TRANSACTION_MANAGER_KEY;

/**
 * 交易管理的数据操作
 *
 * @author Xiho on 2017/1/8.
 */
public class SystemParamsOperation {

    public static final String TAG = "SystemParamsOperation";

    private static SystemParamsOperation instance;
    private SystemParamsSettings instanceSettings;

    private SystemParamsOperation() {
        instanceSettings = getSystemParamsSettings();
        if (instanceSettings == null) {
            instanceSettings = new SystemParamsSettings();
            saveSystemParamsSettings(instanceSettings);
        }
    }

    public static SystemParamsOperation getInstance() {
        if (instance == null) {
            instance = new SystemParamsOperation();
        }
        return instance;
    }

    public void init(String serialNumStart,
                     String batchNumStart,
                     int purchaseOrderStyle,
                     int correctFrequency,
                     int transactionNumber,
                     boolean printNegative,
                     int nonConnection,
                     boolean stateSecret,
                     boolean shieldAuthorizationCard,
                     int nonConnectionChoice,
                     boolean eCashVisaExemption) {
        SystemParamsSettings bean = getSystemParamsSettings();
        bean.setSerialNum(serialNumStart);
        bean.setBatchNumStart(batchNumStart);
        bean.setPurchaseOrderStyle(purchaseOrderStyle);
        bean.setCorrectFrequency(correctFrequency);
        bean.setTransactionNumber(transactionNumber);
        bean.setPrintNegative(printNegative);
        bean.setNonConnection(nonConnection);
        bean.setStateSecret(stateSecret);
        bean.setShieldAuthorizationCard(shieldAuthorizationCard);
        bean.setNonConnectionChoice(nonConnectionChoice);
        bean.setCashVisaExemption(eCashVisaExemption);
        saveSystemParamsSettings(bean);
    }

    public boolean isDownloadParamsOnce() {
        SystemParamsSettings params = getSystemParamsSettings();
        return params.isDownloadParamsOnce();
    }

    public void saveDownloadParamsOnce(boolean downloadParamsOnce) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setDownloadParamsOnce(downloadParamsOnce);
        saveSystemParamsSettings(params);
    }

    public boolean isNeedDownLoadICParams() {
        SystemParamsSettings params = getSystemParamsSettings();
        return params.isNeedDownLoadICParams();
    }

    public void saveNeedDownLoadICParams(boolean needDownLoadICParams) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setNeedDownLoadICParams(needDownLoadICParams);
        saveSystemParamsSettings(params);
    }

    /**
     * 设置流水号
     *
     * @param serialNumber 起始流水号
     */
    public void saveSerialNumber(String serialNumber) {
        if (TextUtils.isEmpty(serialNumber)) {
            return;
        }
        SystemParamsSettings params = getSystemParamsSettings();
        params.setSerialNum(serialNumber);
        saveSystemParamsSettings(params);
    }


    /**
     * 设置批次号
     *
     * @param batchNumber 起始批次号
     */
    public void saveBatchNumber(String batchNumber) {
        if (TextUtils.isEmpty(batchNumber)) {
            return;
        }
        SystemParamsSettings params = getSystemParamsSettings();
        params.setBatchNumStart(batchNumber);
        saveSystemParamsSettings(params);
    }

    /**
     * 流水号自增
     */
    private void incrementSerialNum() {
        SystemParamsSettings params = getSystemParamsSettings();
        String currentSerialNum = params.getCurrentSerialNum();
        if (!TextUtils.isEmpty(currentSerialNum)) {
            String newStr = currentSerialNum.replaceAll("^(0+)", "");
            try {
                if (TextUtils.isEmpty(newStr)) {
                    newStr = "1";
                }
                int transNum = Integer.valueOf(newStr);
                if (transNum >= 999999) {
                    transNum = 1;
                } else {
                    transNum++;  //自增
                }
                String transNumFormat = String.format(Locale.getDefault(), "%06d", transNum);
                LogUtil.e(TAG, "最新流水号: " + transNumFormat);
                params.setSerialNum(transNumFormat);
                saveSystemParamsSettings(params);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 获取当前流水号
     */
    public String getCurrentSerialNum() {
        SystemParamsSettings params = getSystemParamsSettings();
        return params.getCurrentSerialNum();
    }

    /**
     * 获取当前流水号自增后流水号
     */
    public String getIncrementSerialNum() {
        LogUtil.e(TAG, "获取当前流水号自增后流水号: getIncrementSerialNum");
        incrementSerialNum();
        SystemParamsSettings params = getSystemParamsSettings();
        return params.getCurrentSerialNum();
    }

    /**
     * 当前流水号的前一个位
     */
    public String getPreSerialNum(String serialNum) {
        if (!TextUtils.isEmpty(serialNum)) {
            String newStr = serialNum.replaceAll("^(0+)", "");
            int transNum = Integer.valueOf(newStr);
            transNum--;
            return String.format(Locale.getDefault(), "%06d", transNum);
        }
        return null;
    }


    /**
     * 重置流水号和批次号
     */
    public void resetSerialAndBatch() {
        SystemParamsSettings params = getSystemParamsSettings();
        SharedPreferencesUtil.clearByKey(TRANSACTION_MANAGER_KEY);
        params.setSerialNum("000001");
        params.setBatchNumStart("000001");
        saveSystemParamsSettings(params);
    }

    /**
     * 套打签购单样式
     *
     * @param purchaseOrderStyle 样式
     */
    public void savePurchaseOrderStyle(int purchaseOrderStyle) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setPurchaseOrderStyle(purchaseOrderStyle);
        saveSystemParamsSettings(params);
    }

    /**
     * 冲正重发次数
     *
     * @param correctFrequency 冲正重发次数
     */
    public void saveCorrectFrequency(int correctFrequency) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setCorrectFrequency(correctFrequency);
        saveSystemParamsSettings(params);
    }

    /**
     * 最大交易笔数设置
     *
     * @param transactionNumber 最大交易笔数
     */
    public void saveTransactionNumber(int transactionNumber) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setTransactionNumber(transactionNumber);
        saveSystemParamsSettings(params);
    }

    /**
     * 撤销类交易打印负号
     *
     * @param printNegative 是否撤销类交易打印负号
     */
    public void savePrintNegative(boolean printNegative) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setPrintNegative(printNegative);
        saveSystemParamsSettings(params);
    }

    /**
     * 非接交易通道开关
     *
     * @param nonConnection 非接交易通道开关
     */
    public void saveNonConnection(int nonConnection) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setNonConnection(nonConnection);
        saveSystemParamsSettings(params);
    }

    /**
     * 是否支持国密
     *
     * @param stateSecret 是否支持国密
     */
    public void saveStateSecret(boolean stateSecret) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setStateSecret(stateSecret);
        saveSystemParamsSettings(params);
    }

    /**
     * 是否屏蔽预授权卡号
     *
     * @param shieldAuthorizationCard 是否屏蔽预授权卡号
     */
    public void saveShieldAuthorizationCard(boolean shieldAuthorizationCard) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setShieldAuthorizationCard(shieldAuthorizationCard);
        saveSystemParamsSettings(params);
    }

    /**
     * 非接选择
     *
     * @param nonConnectionChoice 非接选择
     */
    public void saveNonConnectionChoice(int nonConnectionChoice) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setNonConnectionChoice(nonConnectionChoice);
        saveSystemParamsSettings(params);
    }

    /**
     * 电子现金免签
     *
     * @param eCashVisaExemption 电子现金免签
     */
    public void saveECashVisaExemption(boolean eCashVisaExemption) {
        SystemParamsSettings params = getSystemParamsSettings();
        params.setCashVisaExemption(eCashVisaExemption);
        saveSystemParamsSettings(params);
    }

    /**
     * @return 交易管理设置
     */
    public SystemParamsSettings getSystemParamsSettings() {
        LogUtil.e(TAG, "getSystemParamsSettings appId:" + MyApplication.getInstance().getPackageName() + " cache path:" + MyApplication.getInstance().getCacheDir());
        if(instanceSettings == null) {
            Object obj = SharedPreferencesUtil.readObj(TRANSACTION_MANAGER_KEY);
            if (obj instanceof SystemParamsSettings) {
                instanceSettings = (SystemParamsSettings) obj;
            } else {
                instanceSettings = new SystemParamsSettings();
                saveSystemParamsSettings(instanceSettings);
            }
        }
        return instanceSettings;
    }

    public void saveSystemParamsSettings(SystemParamsSettings systemParamsSettings) {
        LogUtil.e(TAG, "saveSystemParamsSettings appId:" + MyApplication.getInstance().getPackageName() + " cache path:" + MyApplication.getInstance().getCacheDir());
        LogUtil.e(TAG, "saveSystemParamsSettings SerialNum:" + systemParamsSettings.getCurrentSerialNum());
        this.instanceSettings = systemParamsSettings;
        SharedPreferencesUtil.saveObj(systemParamsSettings, TRANSACTION_MANAGER_KEY);
    }

    public void clearTransactionConfigData() {
        SharedPreferencesUtil.clearByKey(TRANSACTION_MANAGER_KEY);
    }


}
